package cn.stylefeng.guns.sys.modular.tao.outController;


import cn.stylefeng.guns.sys.modular.api.sdk.PageUtils;
import cn.stylefeng.guns.sys.modular.api.sdk.Query;
import cn.stylefeng.guns.sys.modular.tao.entity.Classification;
import cn.stylefeng.guns.sys.modular.tao.entity.MemberSpecs;
import cn.stylefeng.guns.sys.modular.tao.model.params.ClassificationParam;
import cn.stylefeng.guns.sys.modular.tao.model.result.ClassificationResult;
import cn.stylefeng.guns.sys.modular.tao.model.result.GoodsResult;
import cn.stylefeng.guns.sys.modular.tao.service.*;
import cn.stylefeng.guns.sys.modular.tao.shiUtil.AesUtil;
import cn.stylefeng.guns.sys.modular.tao.shiUtil.HttpRequest;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/Common")
@CrossOrigin("*")
public class CommonController {

    @Autowired
    RechargeRecordService rechargeRecordService;
    @Autowired
    WxUserService wxUserService;
    @Autowired
    MemberSpecsService memberSpecsService;
    @Autowired
    MemberService memberService;
    @Autowired
    GoodsService goodsService;
    @Autowired
    StockService stockService;

    //商品分类
    @Autowired
    private ClassificationService classificationService;

    /**
     * 帮助中心
     */
    @Autowired
    private TaoHelpServices taoHelpService;


    /**
     * 图文视频表
     */
    @Autowired
    private PictureVideoService pictureVideoService;


    /**
     * 成为付费会员
     */
    @RequestMapping("/BecomeMember")
    @ResponseBody
    @ApiOperation(value = "成为付费会员", httpMethod = "POST", notes = "成为付费会员", tags = {"会员"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "memberSpecsId", value = "所选会员类型", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "openId", value = "openId", dataType = "Integer", paramType = "query"),
    })
    public ResponseData BecomeMember(HttpServletResponse response , String userId,Integer memberSpecsId,String openId ) {
        if(userId!=null&&memberSpecsId!=null&&openId!=null&&userId!=""&&openId!=""){
            return memberService.BecomeMember(userId,memberSpecsId,openId);
        }else{
            ResponseData date = new ResponseData();
            date.setCode(500);
            date.setMessage("参数为空！");
            return date;
        }

    }


    /**
         * 方法描述
         */
        @RequestMapping("/getAllGoods")
        @ResponseBody
        public PageUtils getAllGoods(@RequestParam Map<String, Object> params){
            //查询列表数据
            String page = params.get("offset").toString();//页码
            String limit = params.get("limit").toString();//每页条数
            String fullname = params.get("fullname").toString();
            params.put("offset", (Integer.valueOf(page) - 1) * (Integer.valueOf(limit).intValue()));
            params.put("limit", limit);
            params.put("fullname", fullname);
            Query query = new Query(params);
            List<GoodsResult> goodsList = goodsService.lists(query);
            int total = goodsService.counts(query);
            PageUtils pageUtils = new PageUtils(goodsList, total);
            return pageUtils;
        }
    /**
     * 获取会员价格
     */
    @RequestMapping("/getAllVipPrice")
    @ResponseBody
    @ApiOperation(value = "获取会员价格", httpMethod = "POST", notes = "获取会员价格", tags = {"会员"})
    @ApiImplicitParams({
    })
    public ResponseData getAllVipPrice(HttpServletResponse response) {
        ResponseData date = new ResponseData();
        List<MemberSpecs> MemberSpecs = memberSpecsService.getAll();
        date.setCode(200);
        date.setData(MemberSpecs);
        return date;
    }

     /**
          * 根据id查询vip详情
          */
         @RequestMapping("/getMemberById")
         @ResponseBody
         public ResponseData getMemberById(HttpServletResponse response,Integer id) {
             ResponseData date = new ResponseData();
             MemberSpecs MemberSpecs=   memberSpecsService.getMemberById(id);
             date.setData(MemberSpecs);
             return date;
         }

    /**
     * 根据id 查商品详情
     */
    @RequestMapping("/getGoodsByGoodsId")
    @ResponseBody
    public ResponseData getGoodsByGoodsId(HttpServletResponse response,String id){
        return ResponseData.success(goodsService.getGoodsByGoodsId(id));
    }



    /**
     * 根据 商品表的 pictureVideoId 查询 图文和视频 详情
     */
    @RequestMapping("/getPictureVideoDetails")
    @ResponseBody
    public ResponseData getPictureVideoDetails(String pictureVideoId){
        if(ToolUtil.isEmpty(pictureVideoId)){
            return ResponseData.success("暂无图文或视频！");
        }else{
            return ResponseData.success(200,"查询成功！",pictureVideoService.getById(pictureVideoId));
        }
    }







    /**
     * 根据商品id查规格
     */
    @RequestMapping("/getGoodsSpecsByGoodsId")
    @ResponseBody
    public ResponseData getGoodsSpecsByGoodsId(HttpServletResponse response,String id){
        return ResponseData.success(stockService.getGoodsSpecsByGoodsId(id));
    }

    /**
     * 根据 商品名称 模糊查商品详情
     */
    @RequestMapping("/getGoodsByName")
    @ResponseBody
    public ResponseData getGoodsByName(HttpServletResponse response,String name,String index,String end){
        ResponseData date = new ResponseData();
        List<GoodsResult> goods = goodsService.getGoodsByName(name,index,end);
        date.setData(goods);
        return date;
    }



    @ApiOperation(value = "查询商品分类数据接口")
    @RequestMapping(value = "/commodityClassification", method = RequestMethod.POST)
    @ResponseBody
    public Object commodityClassification(){
        //QueryWrapper<Classification> queryWrapper = new QueryWrapper<>();
        //queryWrapper.eq("parent_code",-1);
        ClassificationParam classification = new ClassificationParam();
        classification.setParentCode(-1);
        return ResponseData.success(classificationService.getGoodsType(classification));
    }



    @ApiOperation(value = "根据分类查询商品数据")
    @RequestMapping(value = "/queryDataAccordingToClassification", method = RequestMethod.POST)
    @ResponseBody
    public Object queryDataAccordingToClassification(String classificationId){
        String id = "";
        ClassificationParam classification = new ClassificationParam();
        classification.setParentCode(Integer.parseInt(classificationId));
        List<Classification> classificationList = classificationService.getGoodsType(classification);
        for (int i = 0; i<classificationList.size(); i++){
             id += classificationList.get(i).getId() + ",";
        }
        String ids = id.substring(0,id.length()-1);
        //根据分类查询数据
        List<GoodsResult> list = goodsService.queryDataAccordingToClassification(ids);
        return ResponseData.success(list);
    }




    @ApiOperation(value = "查询帮助中心数据")
    @RequestMapping(value = "/helpCenterList", method = RequestMethod.POST)
    @ResponseBody
    public Object helpCenterList(){
        return ResponseData.success(taoHelpService.list());
    }




    @ApiOperation("获取微信小程序的openid")
    @ResponseBody
    @RequestMapping(value = "/decodeUserInfo", method = RequestMethod.GET)
    public Map getOpenid(String code, String encryptedData, String iv ) throws Exception{

        Map<String,Object> map = new HashMap<String,Object>();
        //code = "081ZExyD0qnP4j2LV5yD0hFLyD0ZExyK";
        //登录凭证不能为空
        if (code == null || code.length() == 0) {
            map.put("status", 0);
            map.put("msg", "code 不能为空");
            System.out.println("map1:" + map);
            return map;
        }
        //小程序唯一标识   (在微信小程序管理后台获取)
        String wxspAppid = "wxe09464398e58d00c";
        //小程序的 app secret (在微信小程序管理后台获取)
        String wxspSecret = "9e646f2262d815c45a35df114e815906";
        //授权（必填）
        String grant_type = "authorization_code";
        //////////////// 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid ////////////////
        //请求参数
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
        //发送请求
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        //解析相应内容（转换成json对象）
        JSONObject json = JSONObject.parseObject(sr);
        //获取会话密钥（session_key）
        String session_key = json.get("session_key").toString();
        //用户的唯一标识（openid）
        String openid = (String) json.get("openid");
        System.out.println("openid:" + openid);
        //////////////// 2、对encryptedData加密数据进行AES解密 ////////////////
        try {
            String result = AesUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
            if (null != result && result.length() > 0) {
                map.put("status", 1);
                map.put("msg", "解密成功");

                JSONObject userInfoJSON = JSONObject.parseObject(result);
                Map<String,Object> userInfo = new HashMap<String,Object>();
                userInfo.put("openId", userInfoJSON.get("openId"));
                userInfo.put("nickName", userInfoJSON.get("nickName"));
                userInfo.put("gender", userInfoJSON.get("gender"));
                userInfo.put("city", userInfoJSON.get("city"));
                userInfo.put("province", userInfoJSON.get("province"));
                userInfo.put("country", userInfoJSON.get("country"));
                userInfo.put("avatarUrl", userInfoJSON.get("avatarUrl"));
                userInfo.put("unionId", userInfoJSON.get("unionId"));
                map.put("userInfo", userInfo);
                System.out.println("map2:" + map);
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("status", 0);
        map.put("msg", "解密失败");
        System.out.println("map3:" + map);
        return map;
    }












}









